package com.attunlcok.unlock.task;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;

import com.attunlcok.common.utils.DateUtils;
import com.attunlcok.unlock.constant.UnlockStatus;
import com.attunlcok.unlock.domain.AttUnlockRecord;
import com.attunlcok.unlock.service.IAttUnlockRecordService;
import com.attunlcok.system.service.ISysConfigService;

/**
 * 解锁状态查询任务
 * 定时查询未出结果的解锁任务状态
 * 
 * @author ruoyi
 */
@Component("unlockStatusTask")
public class UnlockStatusTask {
    
    private static final Logger log = LoggerFactory.getLogger(UnlockStatusTask.class);
    
    @Autowired
    private IAttUnlockRecordService unlockRecordService;
    
    @Autowired
    private ISysConfigService configService;
    
    // 状态输出的正则表达式
    private static final Pattern STATUS_PATTERN = Pattern.compile("STATUS:(\\d+)\\s+(.*)");
    
    /**
     * 每小时执行一次，查询未完成解锁任务的状态
     * 对于已有请求编号的任务，调用Python脚本查询结果
     */
    public void queryUnlockStatus() {
        log.info("开始执行解锁状态查询任务");
        
        try {
            // 获取Python路径和最大重试次数配置
            String pythonPath = configService.selectConfigByKey("pythonPath");
            if (pythonPath == null || pythonPath.isEmpty()) {
                pythonPath = "python"; // 默认值
            }
            
            String maxRetryStr = configService.selectConfigByKey("statusMaxRetry");
            int maxRetry = 10; // 默认值
            if (maxRetryStr != null && !maxRetryStr.isEmpty()) {
                try {
                    maxRetry = Integer.parseInt(maxRetryStr);
                } catch (NumberFormatException e) {
                    log.warn("解析最大重试次数配置失败，使用默认值10", e);
                }
            }
            
            // 获取所有已确认邮件状态的解锁记录
            AttUnlockRecord queryRecord = new AttUnlockRecord();
            queryRecord.setUnlockStatus(UnlockStatus.CONFIRMED); // 已确认邮件状态
            
            List<AttUnlockRecord> records = unlockRecordService.selectAttUnlockRecordList(queryRecord);
            log.info("查询到{}条待查询状态的解锁记录", records.size());
            
            for (AttUnlockRecord record : records) {
                try {
                    // 如果没有请求编号，则跳过
                    if (record.getRequestNumber() == null || record.getRequestNumber().isEmpty()) {
                        log.debug("记录ID: {}，IMEI: {} 缺少请求编号，跳过查询", record.getId(), record.getImei());
                        continue;
                    }
                    
                    // 获取当前重试次数，如果超过最大重试次数，则不再查询
                    String retryCountStr = record.getRemark();
                    int retryCount = 0;
                    if (retryCountStr != null && !retryCountStr.isEmpty()) {
                        try {
                            retryCount = Integer.parseInt(retryCountStr);
                        } catch (NumberFormatException e) {
                            // 忽略转换错误
                            log.debug("解析重试次数失败: {}", retryCountStr);
                        }
                    }
                    
                    if (retryCount >= maxRetry) {
                        log.info("记录ID: {}，IMEI: {} 已达到最大重试次数: {}, 不再查询", 
                                record.getId(), record.getImei(), maxRetry);
                        continue;
                    }
                    
                    // 构建Python命令
                    String command = String.format("%s -m att_unlock.main status --id %d --request-number %s --imei %s --retry %d",
                            pythonPath, record.getId(), record.getRequestNumber(), record.getImei(), retryCount);
                    
                    log.info("执行命令: {}", command);
                    
                    // 执行命令
                    Process process = Runtime.getRuntime().exec(command);
                    
                    // 读取输出
                    BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                    String line;
                    StringBuilder output = new StringBuilder();
                    while ((line = reader.readLine()) != null) {
                        output.append(line).append("\n");
                    }
                    
                    // 读取错误输出
                    BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
                    StringBuilder errorOutput = new StringBuilder();
                    while ((line = errorReader.readLine()) != null) {
                        errorOutput.append(line).append("\n");
                    }
                    
                    // 等待命令执行完成
                    int exitCode = process.waitFor();
                    
                    // 更新重试次数
                    record.setRemark(String.valueOf(retryCount + 1));
                    record.setUpdateTime(DateUtils.getNowDate());
                    
                    if (exitCode == 0) {
                        log.info("命令执行成功，输出: {}", output.toString());
                        
                        // 尝试从输出中解析状态码
                        String outputStr = output.toString();
                        Matcher matcher = STATUS_PATTERN.matcher(outputStr);
                        if (matcher.find()) {
                            try {
                                int pythonStatus = Integer.parseInt(matcher.group(1));
                                String statusDesc = matcher.group(2);
                                
                                // 转换Python状态为内部状态
                                String newStatus = UnlockStatus.fromPythonStatus(pythonStatus);
                                log.info("解析到Python返回状态: {}, 状态描述: {}, 转换为内部状态: {}", 
                                         pythonStatus, statusDesc, newStatus);
                                
                                // 更新记录状态
                                record.setUnlockStatus(newStatus);
                                
                                // 更新描述信息
                                if (statusDesc != null && !statusDesc.isEmpty()) {
                                    record.setErrorMsg(statusDesc);
                                }
                            } catch (NumberFormatException e) {
                                log.error("解析Python状态码时出错", e);
                            }
                        } else {
                            log.warn("未从输出中解析到状态码: {}", outputStr);
                        }
                    } else {
                        log.error("命令执行失败，错误代码: {}，错误输出: {}", exitCode, errorOutput.toString());
                        // 考虑技术失败，但不立即更新状态
                    }
                    
                    // 保存更新
                    unlockRecordService.updateAttUnlockRecord(record);
                    
                } catch (Exception e) {
                    log.error("处理记录时出错，ID: " + record.getId(), e);
                }
            }
            
        } catch (Exception e) {
            log.error("执行解锁状态查询任务时出错", e);
        }
        
        log.info("解锁状态查询任务执行完成");
    }
} 